package com.server.llh.llhserverwork.activity.work;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.ServerNetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.LlhBaseActivity;
import com.server.llh.llhserverwork.activity.my.LoginActivity;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.SerTransWapBean;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.utils.TimeUtils;
import com.server.llh.llhserverwork.utils.ToastTool;

import org.json.JSONException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ZTF on 2017-06-06.
 */

public class QiangDanActivity extends LlhBaseActivity {
    private static final String TAG = "QiangDan";
    @BindView(R.id.titleName)
    TextView titleName;
    @BindView(R.id.main_back)
    ImageButton mainBack;
    @BindView(R.id.leftBtn_RL_title_base)
    RelativeLayout leftBtnRLTitleBase;
    @BindView(R.id.serverName)
    TextView serverName;
    @BindView(R.id.linearLayout1)
    LinearLayout linearLayout1;
    @BindView(R.id.order_list)
    ListView orderList;
    SwipeRefreshLayout refresh_data;
    String userIdStr, orgId, userNameStr, supplierTypeId,
            supplierName, supplierId, orgType,token,partTimeOrg,workOrgStr;
    Map<String,String> waiterOrgList=new HashMap<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        titleName.setText("抢单");
        token = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.TOKEN_STR,
                getApplicationContext());
        userIdStr = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_ID,
                getApplicationContext());
        userNameStr = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_NAMW,
                getApplicationContext());

        supplierId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_ID,
                getApplicationContext());
        supplierName = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_NAME,
                getApplicationContext());
        supplierTypeId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_TYPE,
                getApplicationContext());
        orgId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_ID,
                getApplicationContext());
        orgType = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_TYPE,
                getApplicationContext());
        refresh_data = (SwipeRefreshLayout) this.findViewById(R.id.refresh_data);
        if (LoginActivity.waiterOrgList!=null){
            waiterOrgList= LoginActivity.waiterOrgList;
            try {
            if (waiterOrgList.get("workOrg").toString()!=null){
                workOrgStr=waiterOrgList.get("workOrg").toString();
            }
            }catch (Exception E){
            }
            try {
                if (waiterOrgList.get("partTimeOrg").toString()!=null){
                    partTimeOrg =waiterOrgList.get("partTimeOrg").toString();
                }
            }catch (Exception E){

            }

        }

        try {
            getOrderData();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        refresh_data.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    getOrderData();
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    OrderReceivingAdapter adapter;
    public void getOrderData() throws JSONException, UnsupportedEncodingException {
        LRequest lRequest = new LRequest();
        lRequest.addParam("waiterId", userIdStr);
        lRequest.addParam("token", token);
        if (workOrgStr!=null){
            Log.d(TAG,"workOrgStr=="+workOrgStr);
            lRequest.addParam("workOrg", workOrgStr);
        }
        if (partTimeOrg!=null){
            Log.d(TAG,"partTimeOrg=="+partTimeOrg);
            lRequest.addParam("partTimeOrg", partTimeOrg);
        }
        lRequest.setUriType(UrlsTools.SERVER_TASK_REQ);
        lRequest.setUri(ServerPort.SEARCH_AUTOMA_JSON);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                T.showAnimErrorToast(getApplicationContext(), "请求超时!");
            }

            @Override
            public void onNext(String responseBean, String code) {
                Log.d(TAG, "responseBean==" + responseBean);
                if (responseBean != null&&"200".equals(code)) {
                    serTransWapBeen = new Gson().fromJson(responseBean,
                            new TypeToken<List<SerTransWapBean>>() {
                            }.getType());
                    if (orderList.getAdapter() == null) {
                        adapter = new OrderReceivingAdapter(serTransWapBeen, getApplicationContext());
                        orderList.setAdapter(adapter);
                    } else {
                        adapter.setListDevice(serTransWapBeen);
                        adapter.notifyDataSetChanged();
                    }
                }else{
                    T.showAnimToast(getApplicationContext(),"暂时没有数据！");
                }
            }
        });
    }
    List<SerTransWapBean> serTransWapBeen=new ArrayList<>();

    class OrderReceivingAdapter extends BaseAdapter {

        private List<SerTransWapBean> listDevice;

        public List<SerTransWapBean> getListDevice() {
            return listDevice;
        }

        public void setListDevice(List<SerTransWapBean> listDevice) {
            this.listDevice = listDevice;
        }

        private Context context;

        public OrderReceivingAdapter(List<SerTransWapBean> listDevice, Context context) {
            this.context = context;
            this.listDevice = listDevice;
        }

        @Override
        public int getCount() {
            return listDevice == null ? 0 : listDevice.size();
        }

        @Override
        public Object getItem(int arg0) {
            return listDevice == null ? null : listDevice.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            Holder h = new Holder();
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.grab_item, null);
                h.client_name = (TextView) convertView
                        .findViewById(R.id.client_name);
                h.client_age = (TextView) convertView
                        .findViewById(R.id.client_age);
                h.order_time = (TextView) convertView
                        .findViewById(R.id.order_time);
                h.order_server_m = (TextView) convertView
                        .findViewById(R.id.order_server_m);
                h.client_num = (TextView) convertView
                        .findViewById(R.id.client_num);
                h.client_address = (TextView) convertView
                        .findViewById(R.id.client_address);
                h.client_server = (TextView) convertView
                        .findViewById(R.id.client_server);
                h.client_server_time = (TextView) convertView
                        .findViewById(R.id.client_server_time);

                h.server_time = (TextView) convertView
                        .findViewById(R.id.server_time);

                h.subscribe_server_order = (TextView) convertView
                        .findViewById(R.id.subscribe_server_order);

                h.subscribe_ju_order = (TextView) convertView
                        .findViewById(R.id.subscribe_ju_order);
                convertView.setTag(h);
            } else {
                h = (Holder) convertView.getTag();
            }
            final SerTransWapBean myDevice = listDevice.get(position);
            h.client_name.setText("" + myDevice.getCustomerName());
            h.client_age.setText("");
            h.order_time.setText(""
                    + TimeUtils.dateToString(myDevice.getAddTime()));
            h.client_num.setText("" + myDevice.getSerTransId());
//			h.client_address.setText("" + myDevice.getOrgName());
            if (myDevice.getRemark() != null) {
                h.client_server.setText("描述:" + myDevice.getRemark());
            } else {
                h.client_server.setVisibility(View.GONE);
            }
            h.client_address.setText("" + myDevice.getServiceName());
            String startTime = TimeUtils.dateToString(myDevice
                    .getSerStartTime());
            String endTimeStr = TimeUtils
                    .dateToString(myDevice.getSerEndTime());
            h.server_time.setText(""
                    + startTime.substring(5, startTime.length() - 3) + "--"
                    + endTimeStr.substring(5, endTimeStr.length() - 3));
            if ("1".equals(myDevice.getTransStatus())) {
                h.subscribe_ju_order.setVisibility(View.INVISIBLE);
                h.subscribe_server_order.setText("抢单");
            } else {
                h.subscribe_ju_order.setVisibility(View.VISIBLE);
                h.subscribe_server_order.setText("接单");
            }
            if ("10".equals(myDevice.getTransStatus())) {
                h.subscribe_ju_order.setVisibility(View.INVISIBLE);
                h.subscribe_server_order.setText("接单");
            }


            h.subscribe_ju_order.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    long serTransId = myDevice.getSerTransId();
                    String transStatus = "3";
                    try {
                        uploadReSend(myDevice.getCustomerId(),myDevice.getPackDetailId()+"",serTransId, transStatus,position);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            h.subscribe_server_order.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    long serTransId = myDevice.getSerTransId();
                    String transStatus = "";
                    if ("1".equals(myDevice.getTransStatus())) {
                        transStatus = "5";
                    } else if ("2".equals(myDevice.getTransStatus())) {
                        transStatus = "4";
                    }
                    try {
                        uploadReSend(myDevice.getCustomerId(),myDevice.getPackDetailId()+"",serTransId, transStatus,position);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return convertView;
        }

        class Holder {
            TextView client_name, client_age, order_time, order_server_m,
                    client_num, client_address, client_server,
                    client_server_time, server_time, subscribe_server_order,
                    subscribe_ju_order;
        }
    }

    /**
     * 抢单执行
     *
     * @param serTransId
     * @param transStatus
     * @throws JSONException
     */
    private void uploadReSend(String customerId,String packDetailId,long serTransId, String transStatus, final int position) throws JSONException {
        try {
            LRequest lRequest = new LRequest();
            lRequest.addParam("token", token);
            lRequest.addParam("customerId", customerId);
            lRequest.addParam("waitersId", userIdStr);
            lRequest.addParam("transStatus", transStatus);
            lRequest.addParam("packDetailId", packDetailId);
            if (partTimeOrg!=null){
                lRequest.addParam("partTimeOrg", partTimeOrg);
            }
            if (workOrgStr!=null){
                lRequest.addParam("workOrg", workOrgStr);
            }
            lRequest.addParam("waitersName", URLEncoder.encode(userNameStr,"UTF-8"));
            lRequest.addParam("serTransId", serTransId);
            lRequest.setUri(ServerPort.UPDATE_TASK_JSON);
            lRequest.setUriType(UrlsTools.SERVER_TASK_REQ);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    T.showAnimErrorToast(getApplicationContext(), "请求超时!");
                }

                @Override
                public void onNext(String responseBean, String code) {
                    if (responseBean != null&&"200".equals(code)) {
                        ToastTool.showText(getApplicationContext(),"抢单成功！");
                        try {
                            getOrderData();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }else{
                        try {
                            ToastTool.showText(getApplicationContext(),"抢单失败！");
                            closeProgress();
                        }catch (Exception E){

                        }

                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showProgress() {
        try {
            if (refresh_data != null && refresh_data.isRefreshing()) {
                refresh_data.setRefreshing(false);
            }
            showProgress(QiangDanActivity.this);
        } catch (Exception e) {

        }

    }

    @Override
    protected INetRequestManager getRequestManager() {
        return ServerNetRequestManager.getInstance();
    }

    @Override
    public void hideProgress() {
        try {
            if (refresh_data != null && refresh_data.isRefreshing()) {
                refresh_data.setRefreshing(false);
            }
            closeProgress();
        } catch (Exception e) {

        }
    }

    @Override
    protected int getlayout() {
        return R.layout.llh_my_list;
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void doBasess() {
    }

    @OnClick(R.id.main_back)
    public void onViewClicked() {
        onBackPressed();
    }
}
